#!/bin/sh

BASEDIR="${BASEDIR:-$(dirname -- $0)/..}"
BASEDIR="$(readlink -f -- $BASEDIR)"

. "${BASEDIR}/functions"

${MAKEANN} ${BASEDIR}/ringback.sln ${BASEDIR}/forwarding1
report "makeann forwarding1"

RTPP_ARGS_COMM="-T5 --bridge_symmetric -d dbug -l 0.0.0.0 -6 /:: \
  --config forwarding/rtpproxy.conf \
  --dso ../modules/dtls_gw/.libs/rtpp_dtls_gw_debug.so"

RTPP_LOGFILE_A="dtls_gw.a.rlog"
RTPP_OUTFILE_A="dtls_gw.a.rout"
RTPP_ARGS_A="${RTPP_ARGS_COMM} -r ${RECORD_DIR}"
RTPP_SOCKFILE_A="/tmp/dtls_gw.a.sock"

RTPP_LOGFILE_F="dtls_gw.f.rlog"
RTPP_OUTFILE_F="dtls_gw.f.rout"
RTPP_ARGS_F="${RTPP_ARGS_COMM} -i"
RTPP_SOCKFILE_F="/tmp/dtls_gw.f.sock"

RTPP_LOGFILE_O="dtls_gw.o.rlog"
RTPP_OUTFILE_O="dtls_gw.o.rout"
RTPP_ARGS_O="${RTPP_ARGS_COMM} -P -r ${RECORD_DIR} -S ${RECORD_SPL_DIR}"
RTPP_SOCKFILE_O="/tmp/dtls_gw.o.sock"

RTPP_LOGFILE="dtls_gw.o.rlog"
RTPP_OUTFILE="session_timeouts.rout${j}.${socket_idx}"

RTPP_SOCKFILE="${RTPP_SOCKFILE_A}" RTPP_LOGFILE="${RTPP_LOGFILE_A}" \
 RTPP_OUTFILE="${RTPP_OUTFILE_A}" rtpproxy_start ${RTPP_ARGS_A}
report "rtpproxy GenA start on ${RTPP_SOCKFILE_A}"
RTPP_PID_A="${TMP_PIDFILE}"

RTPP_SOCKFILE="${RTPP_SOCKFILE_F}" RTPP_LOGFILE="${RTPP_LOGFILE_F}" \
 RTPP_OUTFILE="${RTPP_OUTFILE_F}" rtpproxy_start ${RTPP_ARGS_F}
RTPP_START_RC=${?}
if [ ${RTPP_START_RC} -ne 0 ]
then
  TMP_PIDFILE=${RTPP_PID_A} TMP_LOGFILE="/dev/null" rtpproxy_stop TERM
fi
report_rc ${RTPP_START_RC} "rtpproxy Fwd start on ${RTPP_SOCKFILE_F}"
RTPP_PID_F="${TMP_PIDFILE}"

RTPP_SOCKFILE="${RTPP_SOCKFILE_O}" RTPP_LOGFILE="${RTPP_LOGFILE_O}" \
 RTPP_OUTFILE="${RTPP_OUTFILE_O}" rtpproxy_start ${RTPP_ARGS_O}
RTPP_START_RC=${?}
if [ ${RTPP_START_RC} -ne 0 ]
then
  TMP_PIDFILE=${RTPP_PID_A} TMP_LOGFILE="/dev/null" rtpproxy_stop TERM
  TMP_PIDFILE=${RTPP_PID_F} TMP_LOGFILE="/dev/null" rtpproxy_stop TERM
fi
report_rc ${RTPP_START_RC} "rtpproxy GenO start on ${RTPP_SOCKFILE_O}"
RTPP_PID_O="${TMP_PIDFILE}"

${RPTL_INT} -s "${RPTL_DIR}/examples/dtls.rptl"
report "running dtls.rptl RPTL script"

for i in O F A
do
  eval "RTPP_PID=\${RTPP_PID_${i}} RTPP_LOG=\${RTPP_LOGFILE_${i}}"
  TMP_PIDFILE=${RTPP_PID} TMP_LOGFILE="${RTPP_LOG}" rtpproxy_stop HUP
  eval RTPP_STOP_RC_${i}=${?}
done

report_rc ${RTPP_STOP_RC_O} "wait for rtpproxy GenO shutdown"
report_rc ${RTPP_STOP_RC_A} "wait for rtpproxy GenA shutdown"
report_rc ${RTPP_STOP_RC_F} "wait for rtpproxy Fwd shutdown"

for i in o f a
do
  ${DIFF} "dtls_gw/dtls_gw.output" dtls_gw.${i}.rout
  report "dtls_gw.${i}.rout"
done
